package com.tianpengtech.common.plugin.shiro.realm;

import com.tianpengtech.admin.account.AccountDao;
import com.tianpengtech.admin.permission.PermissionDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.model.account.Account;
import com.tianpengtech.common.model.permission.PermissionDispather;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.List;

public class MyShiroRealm extends AuthorizingRealm {

    public String getName() {
        return "DbRealm";
    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        String accountUserName = (String)principalCollection.getPrimaryPrincipal();
        Account account = AccountDao.ME.queryAccountByUserName(accountUserName);
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        String roleName = account.getStr(account.ROLE);
        info.addRole(roleName);
        List<PermissionDispather> permissionList = PermissionDao.ME.queryPermissionByRole(roleName);
        for(PermissionDispather permission:permissionList){
            String current = permission.getStr(PermissionDispather.PERMISSION);
            String[] values = current.split(",");
            for (String each:values){
                info.addStringPermission(each);
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        String userName = (String)authenticationToken.getPrincipal();
        Account account = AccountDao.ME.queryAccountByUserName(userName);
        SimpleAuthenticationInfo info=null ;
        if(account!=null){
            String accoutUserName = account.getStr(Account.USERNAME);
            String accountUserPass = account.getStr(Account.USERPASS);
            info =  new SimpleAuthenticationInfo(accoutUserName,accountUserPass,getName());
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute(GlobalConfigConstant.SESSION_KEY_ACCOUNT,account);
        }
        return info;
    }
}
